// 判断是否是空
function isEmpty(val) {
  return val === '' || val === null || val === undefined
}

/**
 * 通过a 标签下载文件
 * @param {String} href 下载链接
 */
function downloadInLink(href) {
  if (href) {
    const link = document.createElement('a')
    link.href = href
    link.target = 'targetName'
    link.click()
  }
}

/**
 * 时间格式化
 * @param {Date} timestamp
 * @param {String} format
 * @returns
 */
function timestampToDateTime(timestamp = Date.now(), format = 'yyyy-MM') {
  if (isNaN(timestamp)) {
    return ''
  }
  if (format.length < 4 || 'yyyy-MM-dd HH:mm:ss'.indexOf(format) !== 0) {
    return ''
  }
  const date = new Date(Number(timestamp))
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return format
    .replace('yyyy', year)
    .replace('MM', month > 9 ? month : `0${month}`)
    .replace('dd', day > 9 ? day : `0${day}`)
    .replace('HH', hour > 9 ? hour : `0${hour}`)
    .replace('mm', minute > 9 ? minute : `0${minute}`)
    .replace('ss', second > 9 ? second : `0${second}`)
}

/**
 * 对象数组去重
 * @param {Array} arr
 * @param {String} key
 * @returns
 */
function unique(arr, key) {
  if (!arr) return arr
  if (key === undefined) return [...new Set(arr)]
  const map = {
    string: e => e[key],
    function: e => key(e),
  }
  const fn = map[typeof key]
  const obj = arr.reduce((o, e) => ((o[fn(e)] = e), o), {})
  return Object.values(obj)
}

//加密
function smEncrypt(dataObj) {
  var sm2 = require('sm-crypto').sm2
  let cipherMode = 1 // 1 - C1C3C2，0 - C1C2C3，默认为1
  let msg = dataObj
  if (typeof dataObj != 'string') {
    msg = JSON.stringify(dataObj)
  }
  return sm2.doEncrypt(msg, config.publicKey, cipherMode) // 加密结果
}

// 获取浏览器信息
function getBrowser() {
  var document = window.document,
    navigator = window.navigator,
    agent = navigator.userAgent.toLowerCase(),
    //IE8+支持.返回浏览器渲染当前文档所用的模式
    //IE6,IE7:undefined.IE8:8(兼容模式返回7).IE9:9(兼容模式返回7||8)
    //IE10:10(兼容模式7||8||9)
    IEMode = document.documentMode,
    //chorme
    chrome = window.chrome || false,
    System = {
      //user-agent
      agent: agent,
      //是否为IE
      isIE: window.ActiveXObject || 'ActiveXObject' in window,
      isEdge: agent.indexOf('edge') > -1 || agent.indexOf('edg') > -1, //判断是否IE的Edge浏览器
      //Gecko内核
      isGecko: agent.indexOf('gecko') > 0 && agent.indexOf('like gecko') < 0,
      //webkit内核
      isWebkit: agent.indexOf('webkit') > 0,
      //是否为标准模式
      isStrict: document.compatMode === 'CSS1Compat',

      mobile: !!agent.match(/AppleWebKit.*Mobile.*/i), //是否为移动终端
      isIos: !!agent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/i), //iOS终端
      isAndroid: agent.indexOf('android') > -1 || agent.indexOf('adr') > -1, //Android终端
      //是否支持subtitle
      supportSubTitle: function () {
        return 'track' in document.createElement('track')
      },
      //是否支持scoped
      supportScope: function () {
        return 'scoped' in document.createElement('style')
      },
      //获取IE的版本号
      ieVersion: function () {
        try {
          return agent.match(/msie ([\d.]+)/)[1] || 0
        } catch (e) {
          console.log('error')
          return IEMode
        }
      },
      //Opera版本号
      operaVersion: function () {
        try {
          if (window.opera) {
            return agent.match(/opera.([\d.]+)/)[1]
          } else if (agent.indexOf('opr') > 0) {
            return agent.match(/opr\/([\d.]+)/)[1]
          }
        } catch (e) {
          console.log('error')
          return 0
        }
      },
      //描述:version过滤.如31.0.252.152 只保留31.0
      versionFilter: function () {
        if (arguments.length === 1 && typeof arguments[0] === 'string') {
          var version = arguments[0]
          start = version.indexOf('.')
          if (start > 0) {
            end = version.indexOf('.', start + 1)
            if (end !== -1) {
              return version.substr(0, end)
            }
          }
          return version
        } else if (arguments.length === 1) {
          return arguments[0]
        }
        return 0
      },
    }

  // console.log(agent, 'agentagentagent');

  try {
    //浏览器类型(IE、Opera、Chrome、Safari、Firefox)
    System.type = System.isIE
      ? 'IE'
      : System.isEdge
      ? 'Edge'
      : window.opera || agent.indexOf('opr') > 0
      ? 'Opera'
      : agent.indexOf('chrome') > -1 && agent.indexOf('safari') > -1 && !System.isEdge
      ? 'Chrome' //safari也提供了专门的判定方式
      : agent.indexOf('safari') > -1 && agent.indexOf('chrome') == -1
      ? 'Safari'
      : agent.indexOf('firefox') > 0
      ? 'Firefox'
      : 'unknow'

    //版本号
    System.version =
      System.type === 'IE'
        ? System.ieVersion()
        : System.type === 'Edge'
        ? agent.match(/edg\/([\d\.]+)/)[1]
        : System.type === 'Firefox'
        ? agent.match(/firefox\/([\d.]+)/)[1]
        : System.type === 'Chrome'
        ? agent.match(/chrome\/([\d.]+)/)[1]
        : System.type === 'Opera'
        ? System.operaVersion()
        : System.type === 'Safari'
        ? agent.match(/version\/([\d.]+)/)[1]
        : '0'

    //浏览器外壳
    System.shell = function () {
      //edge
      if (System.type === 'Edge') {
        return 'Edge'
      }
      //遨游浏览器
      if (agent.indexOf('maxthon') > 0) {
        System.version = agent.match(/maxthon\/([\d.]+)/)[1] || System.version
        return '傲游浏览器'
      }
      //QQ浏览器
      if (agent.indexOf('qqbrowser') > 0) {
        System.version = agent.match(/qqbrowser\/([\d.]+)/)[1] || System.version
        return 'QQ浏览器'
      }

      //搜狗浏览器
      if (agent.indexOf('se 2.x') > 0) {
        return '搜狗浏览器'
      }

      //Chrome:也可以使用window.chrome && window.chrome.webstore判断
      if (chrome && System.type !== 'Opera') {
        var external = window.external,
          clientInfo = window.clientInformation,
          //客户端语言:zh-cn,zh.360下面会返回undefined
          clientLanguage = clientInfo.languages

        //猎豹浏览器:或者agent.indexOf("lbbrowser")>0
        if (external && 'LiebaoGetVersion' in external) {
          return '猎豹浏览器'
        }
        //百度浏览器
        if (agent.indexOf('bidubrowser') > 0) {
          System.version = agent.match(/bidubrowser\/([\d.]+)/)[1] || agent.match(/chrome\/([\d.]+)/)[1]
          return '百度浏览器'
        }
        //360浏览器
        if (_mime('type', 'application/vnd.chromium.remoting-viewer')) {
          return '360浏览器'
        }
        return 'Chrome'
      }
      return System.type
    }

    //浏览器名称(如果是壳浏览器,则返回壳名称)
    System.name = System.shell()
    //对版本号进行过滤过处理
    System.version = System.versionFilter(System.version)
  } catch (e) {
    // console.log("error");
  }
  return {
    client: System,
  }
}
// 判断360浏览器
function _mime() {
  if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
    let mimeTypes = navigator.mimeTypes
    for (let i = 0; i < mimeTypes.length; i++) {
      let mimeTypeLi = mimeTypes[i]
      if (mimeTypeLi.type == 'application/x-shockwave-flash') {
        let desc = mimeTypeLi.description.toLowerCase()
        if (desc.indexOf('shockwave') > -1) {
          return true
        }
      }
    }
    return false
  }
}

//获取分辨率
function getResolvingPower() {
  var resolvingPower = {}
  resolvingPower.sysScreen = window.screen.width + '*' + window.screen.height
  resolvingPower.sysResolution =
    window.screen.width * window.devicePixelRatio + '*' + window.screen.height * window.devicePixelRatio
  return resolvingPower
}

// 获取操作系统
function getDetectOS() {
  var sUserAgent = navigator.userAgent
  var isWin = navigator.platform == 'Win32' || navigator.platform == 'Windows'
  var isMac =
    navigator.platform == 'Mac68K' ||
    navigator.platform == 'MacPPC' ||
    navigator.platform == 'Macintosh' ||
    navigator.platform == 'MacIntel'
  if (isMac) return 'Mac'
  var isUnix = navigator.platform == 'X11' && !isWin && !isMac
  if (isUnix) return 'Unix'
  var isLinux = String(navigator.platform).indexOf('Linux') > -1
  if (isLinux) return 'Linux'
  if (isWin) {
    var isWin2K = sUserAgent.indexOf('Windows NT 5.0') > -1 || sUserAgent.indexOf('Windows 2000') > -1
    if (isWin2K) return 'Win2000'
    var isWinXP = sUserAgent.indexOf('Windows NT 5.1') > -1 || sUserAgent.indexOf('Windows XP') > -1
    if (isWinXP) return 'WinXP'
    var isWin2003 = sUserAgent.indexOf('Windows NT 5.2') > -1 || sUserAgent.indexOf('Windows 2003') > -1
    if (isWin2003) return 'Win2003'
    var isWinVista = sUserAgent.indexOf('Windows NT 6.0') > -1 || sUserAgent.indexOf('Windows Vista') > -1
    if (isWinVista) return 'WinVista'
    var isWin7 = sUserAgent.indexOf('Windows NT 6.1') > -1 || sUserAgent.indexOf('Windows 7') > -1
    if (isWin7) return 'Win7'
    var isWin10 = sUserAgent.indexOf('Windows NT 10') > -1 || sUserAgent.indexOf('Windows 10') > -1
    if (isWin10) return 'Win10'
  }
  return 'other'
}

export function parseJsonStr(str) {
  if (str) {
    try {
      return JSON.parse(str)
    } catch {
      return null
    }
  }
  return null
}

export function stringifyObj(obj) {
  if (obj && Object.keys(obj).length) {
    try {
      return JSON.stringify(obj)
    } catch {
      return null
    }
  }
  return null
}

export function getPermissions(list, codes) {
  list.forEach(item => {
    codes.push(item.belongPage)
    if (item.menuVOS && item.menuVOS.length) {
      getPermissions(item.menuVOS, codes)
    }
  })
  return codes
}

export function getMenus(role) {
  const basicMenus = [
    {
      belongPage: 'PSKH_DAILY_ATTENDANCE',
      menuCode: '',
      menuName: '日常考勤',
      menuImagePath: 'outduty_icon',
      menuUrl: '/outdutyNew',
      id: 15,
    },
    {
      belongPage: 'PSKH_WORK_NOTICE',
      menuCode: '',
      menuName: '工作通知',
      menuImagePath: 'notify-icon',
      menuUrl: '/workNotify',
      id: 60,
    },
    {
      belongPage: 'PSKH_SYSTEM_FILE',
      menuCode: '',
      menuName: '制度文件',
      menuImagePath: 'system-icon',
      menuUrl: '/agencyNoticeManage',
      id: 70,
    },
    {
      belongPage: 'PSKH_MEETING_MANAGE',
      menuCode: '',
      menuName: '会议管理',
      menuImagePath: 'meeting_icon',
      menuUrl: '/meet',
      id: 45,
    },
    {
      belongPage: 'PSKH_TASK_MANAGE',
      menuCode: '',
      menuName: '任务管理',
      menuImagePath: 'task-iconicon',
      menuUrl: '/task',
      id: 71,
    },
  ]
  const userPermissions = []
  if (role.isAdminRole) {
    basicMenus.push(
      {
        belongPage: 'PSKH_BONUS_ADD',
        menuCode: '',
        menuName: '加分项',
        menuImagePath: 'addmark_icon',
        menuUrl: '/bonusAll',
        id: 30,
      },
      {
        belongPage: 'PSKH_MINZHU_ASSESS_MANAGE',
        menuCode: '',
        menuName: '测评管理',
        menuImagePath: 'democratic-manager-icon',
        menuUrl: '/evaluationDetail',
        id: 50,
      }
    )
  }
  if (role.isMainRole) {
    basicMenus.push(
      {
        belongPage: 'PSKH_DOCUMENTARY_EDITION',
        menuCode: '',
        menuName: '纪实本',
        menuImagePath: 'record-icon',
        menuUrl: '/leaderboard',
        id: 0,
      },
      {
        belongPage: 'PSKH_EVALUATION_COLUMN',
        menuCode: '',
        menuName: '评议栏',
        menuImagePath: 'comment-icon',
        menuUrl: '/appraistPage',
        id: 10,
      }
    )
  }
  if (role.isPartRole) {
    basicMenus.push(
      {
        belongPage: 'PSKH_DOCUMENTARY_EDITION',
        menuCode: '',
        menuName: '纪实本',
        menuImagePath: 'record-icon',
        menuUrl: '/leaderboard',
        id: 0,
      },
      {
        belongPage: 'PSKH_EVALUATION_COLUMN',
        menuCode: '',
        menuName: '评议栏',
        menuImagePath: 'comment-icon',
        menuUrl: '/appraistPage',
        id: 10,
      }
    )
  }
  if (role.isOrgRole) {
    basicMenus.push(
      {
        belongPage: 'PSKH_DOCUMENTARY_EDITION',
        menuCode: '',
        menuName: '纪实本',
        menuImagePath: 'record-icon',
        menuUrl: '/leaderboard',
        id: 0,
      },
      {
        belongPage: 'PSKH_EVALUATION_COLUMN',
        menuCode: '',
        menuName: '评议栏',
        menuImagePath: 'comment-icon',
        menuUrl: '/appraistPage',
        id: 10,
      },
      {
        belongPage: 'PSKH_BONUS_ADD',
        menuCode: '',
        menuName: '加分项',
        menuImagePath: 'addmark_icon',
        menuUrl: '/bonusNew',
        id: 30,
      },
      {
        belongPage: 'PSKH_MINZHU_ASSESS',
        menuCode: '',
        menuName: '民主测评',
        menuImagePath: 'democratic-icon',
        menuUrl: '/evaluationList',
        id: 40,
      }
    )
  }
  if (role.isNormalRole) {
    basicMenus.push({
      belongPage: 'PSKH_DOCUMENTARY_EDITION',
      menuCode: '',
      menuName: '纪实本',
      menuImagePath: 'record-icon',
      menuUrl: '/board',
      id: 0,
    })
  }
  if (
    role.isApplyRole ||
    role.isRepairRole ||
    role.isBusinessRole ||
    role.isReimburseRole ||
    role.isWeekendRole ||
    role.isOrgRole ||
    role.isPartRole ||
    role.isNormalRole ||
    role.isOtherRole
  ) {
    basicMenus.push({
      belongPage: 'PSKH_DAILY_MANAGE',
      menuCode: '',
      menuName: '日常管理',
      menuImagePath: 'logistics_icon',
      menuUrl: '/daily',
      id: 58,
    })
  }
  const basicMenusNew = [...new Map(basicMenus.map(item => [item.id, item])).values()].sort((a, b) => {
    return a.id - b.id
  })
  const basic = {
    belongPage: 'JXKH_PSKH',
    menuCode: '',
    menuName: '平时考核',
    id: 1,
    menuVOS: basicMenusNew,
  }
  userPermissions.push(basic)
  return userPermissions.sort((a, b) => {
    return a.id - b.id
  })
}

// 年份查询列表
export function selectYearFun(year) {
  const date = new Date()
  let yearEnd = date.getFullYear()
  const month = date.getMonth()
  if (Number(month) === 11) {
    yearEnd = yearEnd + 1
  }
  const data = []
  for (let i = year; i <= yearEnd; i++) {
    data.push({
      value: String(i),
      text: String(i) + '年',
    })
  }
  return data
}

// 数字列表双位展示
export function getDoubleNum(idx) {
  let str = ''
  if (idx < 10) {
    str = '0' + idx
  } else {
    str = idx
  }
  return str
}

export function getFileTypeByName(name) {
  if (name) {
    const dotIndx = name.lastIndexOf('.')
    if (dotIndx !== -1) {
      return name.substring(dotIndx + 1).toLowerCase()
    }
  }
}

export { isEmpty, downloadInLink, timestampToDateTime, unique, smEncrypt, getBrowser, getResolvingPower, getDetectOS }
